package com.juphoon.oauth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juphoon.oauth.core.entity.ServerResponse;
import com.juphoon.oauth.core.listener.AuthenticationListener;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * oauth2 认证失败处理handler
 * @author rongbin.huang
 */
@Component("appAuthenticationFailureHandler")
@Slf4j
public class AppAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {


	@Autowired
	private AuthenticationListener authenticationListener;

    @Autowired
	private ObjectMapper objectMapper;

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
		

		response.setStatus(HttpStatus.BAD_REQUEST.value());
		response.setContentType("application/json;charset=UTF-8");
		String message = exception.getMessage();
		if (exception instanceof BadCredentialsException) {
			message = "password error";
		}

		authenticationListener.loginFail(request, exception);
		response.getWriter().write(objectMapper.writeValueAsString(new ServerResponse(message)));
		
	}

}